package com.ld.poetry.config;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ld.poetry.entity.ResourceConfig;
import com.ld.poetry.service.FileUploadService;
import com.ld.poetry.service.ResourceConfigService;
import com.ld.poetry.utils.CommonConst;
import com.ld.poetry.utils.FileUploadUtils;
import com.ld.poetry.vo.upload.LocalUploadInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Component
public class WebInfoConfigurer implements WebMvcConfigurer {
    @Resource
    private ResourceConfigService resourceConfigService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebInfoHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login", "/admin/**", "/webInfo/getWebInfo", "/webInfo/updateWebInfo");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //swagger
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        //knife4j
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        //jquery等静态文件访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        // 有配置就用配置的路径存放静态资源文件，没有就使用默认的
        ResourceConfig localConfig = resourceConfigService
                .getOne(new LambdaQueryWrapper<ResourceConfig>()
                        .eq(ResourceConfig::getId, CommonConst.UPLOAD_TYPE_KEY_LOCAL));
        String resourcesPath = FileUploadService.DEFAULT_UPLOAD_PATH;
        if(Objects.nonNull( localConfig) && StringUtils.isNotBlank(localConfig.getInfo())){
            //静态资源访问
            resourcesPath = JSON.parseObject(localConfig.getInfo(), LocalUploadInfo.class).getUploadPath();
        }
        log.info("set sara resource path={}",resourcesPath);
        resourcesPath = FileUploadUtils.SYSTEM.toLowerCase().contains("windows") ? "D:" + resourcesPath : resourcesPath;
        registry.addResourceHandler("/sara-resources/**")
                .addResourceLocations("file:" + resourcesPath + "/sara-resources/");
    }
}
